/**
 * Created by lwk on 2018/1/5.
 */

import consts from '@/tools/consts'
import utils from '@/tools/utils'
import upload from '@/tools/upload'
import store from '@/store'
import qs from 'qs'
import axios from 'axios'
import { Toast } from 'vant'

const Tools = {}
Tools.install = function (Vue, options) {
  // 网络请求
  const httpRequest = (option) => {
    // 默认配置
    let defaultOption = {
      // 请求地址
      url: '',
      // 请求参数
      param: {},
      // 请求方法
      method: 'GET',
      // 是否显示loading框
      isShowLoadingTip: true,
      // loading提示信息
      loadingText: '加载中',
      // 是否显示回调信息
      isShowMessage: false,
      // 超时时间
      timeout: 60000
    }
    // 组合成新的配置
    let newOption = Object.assign(defaultOption, option)

    // 处理回调信息和加载框
    const handleMegAndLoading = (message = '', isShowMessage, isSuccess = true) => {
      setTimeout(() => {
        store.dispatch('setLoading', false)
        Toast.clear()
        if (utils.isNotBlank(message) && isShowMessage) {
          if (isSuccess) {
            Toast.success(message)
          } else {
            Toast.fail(message)
          }
        }
      }, 0)
    }

    // 是否显示加载框
    if (newOption.isShowLoadingTip) {
      store.dispatch('setLoading', true)
      Toast.loading({
        duration: 0,
        mask: true,
        message: newOption.loadingText
      })
    }

    // 请求参数
    let methodName = newOption.method.toUpperCase()
    let requestParam = {
      url: newOption.url,
      method: methodName,
      timeout: newOption.timeout,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        common: {
          'Authorization': window.localStorage.getItem('accessToken')
        }
      },
      params: methodName === 'GET' ? defaultOption.param : {},
      data: methodName === 'POST' ? defaultOption.param : {},
      transformRequest: [function (data) {
        return qs.stringify(data)
      }]
    }

    // 开始请求
    return new Promise((resolve, reject) => {
      axios.request(requestParam).then(response => {
        let resultData = response.data
        // 处理回调信息和加载框
        handleMegAndLoading(resultData.message, newOption.isShowMessage,
          resultData.code === consts.HTTP_STATE.OK)
        resolve(resultData)
      }).catch(error => {
        // 处理回调信息和加载框
        handleMegAndLoading('请求失败', newOption.isShowMessage, false)
        reject(error)
      })
    })
  }

  // 是否ios系统
  const isIOS = () => {
    let u = window.navigator.userAgent
    let isIosSystem = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
    return isIosSystem
  }

  // 工具类
  const tools = {
    /**
     * 是否ios系统
     */
    isIOS: isIOS,

    /**
     * 判断是否为空
     * @param obj
     * @returns {boolean}
     */
    isBlank (obj = '') {
      return utils.isBlank(obj)
    },

    /**
     * 判断是否不为空
     * @param obj
     * @returns {boolean}
     */
    isNotBlank (obj = '') {
      return utils.isNotBlank(obj)
    },

    /**
     * Http GET请求
     * @param url
     * @param data
     * @param option
     * @returns {Promise<any>}
     */
    httpGet (option = {}) {
      option['method'] = 'GET'
      return httpRequest(option)
    },

    /**
     * Http POST请求
     * @param url
     * @param data
     * @param option
     * @returns {Promise<any>}
     */
    httpPost (option = {}) {
      option['method'] = 'POST'
      return httpRequest(option)
    },

    /**
     * 判断是否为正确的手机号
     * @param pone
     * @returns {boolean}
     */
    isPhoneAvailable (phone) {
      let myreg = /^[1][3,4,5,7,8][0-9]{9}$/
      if (myreg.test(phone)) {
        return true
      }
      return false
    },

    /**
     * 拨打电话
     */
    callPhone (phone) {
      window.location.href = `tel:${phone}`
    },

    /**
     * 选择图片
     * @param type 0拍照、1资源库
     */
    choosePhoto (type, maxSelectCount = 1) {
      switch (type) {
        case 0: // 拍照
          return upload.takePhoto()
        case 1: // 资源库
          return upload.chooseAlbum1(maxSelectCount)
      }
    },

    /**
     * 上传图片
     * @param uploadUrl
     * @param imageUrl
     * @returns {Promise<any>}
     */
    startUpload (uploadUrl, imageUrl, params = {}) {
      if (Object.prototype.toString.call(imageUrl) === '[object Array]') {
        return upload.multipleUpload(uploadUrl, imageUrl, params)
      }
      return upload.startUpload(uploadUrl, imageUrl, params)
    },

    /**
     * 获取文件/图片显示地址
     */
    getFileHostUrl (url) {
      if (url !== undefined && url != null && url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
        return `${consts.API.fileHost}${url}`
      }
      return url
    },

    /**
     * 判断字段是否空，若为空返回默认值
     * @param str
     * @param defaultStr
     * @returns {*}
     */
    isBlankDefaultStr (str, defaultStr = '') {
      if (utils.isBlank(str)) {
        return defaultStr
      }
      return str
    },

    /**
     * 列表分组
     * @param list
     * @returns {{}}
     */
    getListGroup (list = []) {
      let groupMap = {}
      list.forEach((item, index) => {
        let billcode = item.billcode
        let list1 = groupMap[billcode]
        if (list1 === undefined || list1 == null) {
          list1 = []
        }
        list1.push(item)
        groupMap[billcode] = list1
      })
      return groupMap
    },

    /**
     * 是否有新app版本
     */
    isNewVersion (newVersionNumber) {
      document.addEventListener('deviceready', () => {
        window.cordova.getAppVersion.getVersionNumber(currentVersionNumber => {
          let newVersionList = newVersionNumber.split('.')
          let currentVersionList = currentVersionNumber.split('.')
          let minLength = newVersionList.length < currentVersionList.length ? newVersionList.length : currentVersionList.length
          for (let i = 0; i < minLength; i++) {
            let newValue = newVersionList[0]
            let currentValue = currentVersionList[0]
            if (newValue > currentValue) {
              return true
            }
          }
          if (newVersionList.length > currentVersionList.length) {
            return true
          }
          return false
        })
      }, false)
    },

    /**
     * 获取当前app版本
     */
    getCurrentVersion () {
      document.addEventListener('deviceready', () => {
        window.cordova.getAppVersion.getVersionNumber(currentVersionNumber => {
          return currentVersionNumber
        })
      }, false)
    },

    /**
     * 开始支付宝支付
     */
    startAliPay (data) {
      return new Promise((resolve, reject) => {
        window.cordova.plugins.crosspay.aliPay({
          appId: data.appId,
          order: data.orderStr
        }, () => {
          resolve()
        }, error => {
          reject(error)
        })
      })
    },

    /**
     * 开始微信支付
     */
    startWechatPay (data) {
      return new Promise((resolve, reject) => {
        window.cordova.plugins.crosspay.wechatPay({
          appId: '',
          partnerId: '',
          prepayId: '',
          nonceStr: '',
          timeStamp: '',
          sign: '',
          package: 'Sign=WXPay'
        }, () => {
          resolve()
        }, error => {
          reject(error)
        })
      })
    }
  }
  Vue.prototype.$tools = tools
  Vue.prototype.$consts = consts
}

export default Tools
